<?php
namespace Home\Controller;
use Think\Controller;
use Think\AjaxPage;
use Think\Page;
class GoodsController extends Controller {
	public function _initialize() {
		check_goods();
	}
	
	public function cate_all(){
		$lang = I('lang')?I('lang'):'cn';
		$mod = M('goods_cat');		
		$cate_list = $mod->where(array('cat_id'=>0,'status'=>1))->order('sort_order desc')->select();
		foreach((array)$cate_list as $k=>$v){
			if($lang=='jn'){
				$cate_list[$k]['name'] = $v['en_name'];
			}
		}
		exit(json_encode(array('code'=>200,'data'=>$cate_list)));
	}
	
    public function cate_list(){
		$lang = I('lang')?I('lang'):'cn';
		$mod = M('goods_cat');		
		$cate_list = $mod->where(array('cat_id'=>0,'status'=>1))->order('sort_order desc')->limit(10)->select();
		foreach((array)$cate_list as $k=>$v){
			$v['image'] && $cate_list[$k]['image']=C('WEB_URL').$v['image'];
			if($lang=='jn'){
				$cate_list[$k]['name'] = $v['en_name'];
			}
		}
		exit(json_encode(array('code'=>200,'data'=>$cate_list)));
	}
	
	public function goods_list(){
		$mod = M('goods');	
		$where['status'] = 1;
		$where['is_detele'] = 0;
		$page = I('page')?I('page'):1;
		$cate_id = I('cate_id')?I('cate_id'):'';
		$lang = I('lang')?I('lang'):'cn';
		$where['lang'] = $lang;
		$keyword = I('keyword')?I('keyword'):'';
		$keyword && $where['title'] = array('like','%'.$keyword.'%');
		$cate_id && $where['cat_id'] = $cate_id;
		$page_count=10;	
		$count = $mod->where($where)->count();
		$total_pages=ceil($count/$page_count);		
		$page<1 && $page=1;
		$start_row=($page-1)*$page_count;
		$list = $mod->where($where)->field("id,title,price,inventory,CONCAT('".C('WEB_URL')."',thumb) as thumb")->order('ordid desc,id desc')->limit($start_row,$page_count)->select();
		exit(json_encode(array('code'=>200,'data'=>$list,'rollPage'=>$total_pages,'nowPage'=>$page)));
	}
	public function goods_detail(){
		$id = I('id')?I('id'):'';
		$lang = I('lang')?I('lang'):'';
		if($id){
			$mod = M('goods');	
			$detail = $mod->where(array('id'=>$id))->find();
			$cate = M('goods_cat')->where(array('id'=>$detail['cat_id']))->field('name,en_name')->find();
			$detail['cat_name'] = $lang=='cn'?$cate['name']:$cate['en_name'];
			$detail['resume'] = htmlspecialchars_decode($detail['resume']);
			$detail['thumb'] && $detail['thumb'] = C('WEB_URL').$detail['thumb'];
			$goods_img = M('goods_img')->where(array('goods_id'=>$id))->field("CONCAT('".C('WEB_URL')."',thumb) as thumb")->select();
			$detail['goods_img'][] = array('thumb'=>$detail['thumb']);
			foreach((array)$goods_img as $k=>$v){
				$detail['goods_img'][] = $v;
			}
			if($detail['store_id']){
				$detail['username'] = M('users')->where(array('id'=>$detail['store_id']))->getField('username');
			}else{
				$detail['username'] = '';				
			}
			exit(json_encode(array('code'=>200,'data'=>$detail)));
		}
	}
}